%% segement all the files
FileList = {
   
  %  'mohEEG111.mat'
    %  'Marion12_2504.mat'
      'Tim12_2804.mat'
    %  'Romain12_2904.mat'
    };

%FileList = { 'session2.acq.mat' };
%Fs = 2000; default
Fs = 2000;

window = 6000;
window_movement = 6000;
cov_mat_per_class = 3;%number of covariance matrices per movement
% also this is the number of overlaping windows per movement 
windows_sizes = floor( window_movement / cov_mat_per_class );
overlap = window_movement - window_movement / 8;

X = []; % contains the trials from all classes
Y = []; % contains the classification from all classes

Nclass = 12;
CallClass = cell(Nclass,cov_mat_per_class);
n_channels = 10;

start_of_class = [];
end_of_class = [];

for curFileIx = 1:length(FileList)
   


        load(['D:\temp\subjects\' FileList{curFileIx}]);
        disp(['Subject file:' FileList{curFileIx}]);

        datar = data(:,1:size(data,2)-2); % remove 2 trigger channel at the end

        %trial_channel = data(:,8);
        trial_channel = data(:, size(data,2)-1);

        %class_separation_channel = data(:,9);
        class_separation_channel = data(:, size(data,2));

        classN = length(count_sequence(class_separation_channel,5));  % "5" tags each class


        classRest = classN; % the rest class is always the last

        trialsN = length(count_sequence(trial_channel,5));  % "5" tags each trial
            
        disp(['Classes/Movements detected: ' int2str(classN)]);
        disp(['Total trails detected: ' int2str(trialsN)]);
        disp(['Frequency: ' int2str(Fs)]);

        for m = 1:classN
            
            %Pulsar BIOPAC 
            %[best_index,best_trigger] = generate_trials_postitions_using_discrete_channel(m, trial_channel,class_separation_channel);
            [best_index,best_trigger1,class_start_pos,class_end_pos] = generate_trials_postitions_using_discrete_channel(m, trial_channel,class_separation_channel);
            start_of_class = [start_of_class class_start_pos];
            end_of_class = [end_of_class class_end_pos];
               
            % cut signal
            %index = find(diff(trigger)==1); % because we do it earlier now!!!!
            trials_per_class = zeros(size(datar,2),window,length(best_index));
            disp(['Trials: ' int2str(length(best_index)) ' ' FileList{curFileIx}])

            %get the data for these triggers
            for i=1:length(best_index)
                %calculate a range around the trigger
                shift = 100;
                trials_per_class(:,:,i) = datar(best_index(i)+shift:best_index(i)+shift+window-1,:)';
            end

            X = cat(3,X,trials_per_class); % put all trials together
            Y = cat(1,Y,ones(length(best_index),1) * m);

        end;
        
        %all data is available here for the subject for each class
        
        %COVtest = zeros(size(datar,2),size(datar,2),size(X,3),cov_mat_per_class);
    disp('--------------------------------');% next file
end

%% Perform training 
for c = 1:Nclass

    epochs_per_class = X(:,:,Y==c);

    covv = zeros(size(datar,2),size(datar,2),size(epochs_per_class,3));            

    for j=1:cov_mat_per_class % cut each epoch on several consequal chunks of signal

         for i = 1:size(epochs_per_class,3) % go through all signal epochs


            %calculate cov for the this part of the signal
            buffer = epochs_per_class(:, (j-1) * windows_sizes + 1 : j * windows_sizes ,i);
            covv(:,:,i) = covariances(buffer);

            %calculate the barycenter

         end;

         CallClass{c,j} = mean_covariances(covv,method_mean);
     end;

end;


% disp('Training completed');
% 
% FileList = {
%    
%   %  'mohEEG111.mat'
%       'Marion12_2504.mat'
%     %  'Tim12_2804.mat'
% 
%     };
% 
% %% Classification over X and Y
% 
% for curFileIx = 1:length(FileList)
   
%         load(['D:\temp\subjects\' FileList{curFileIx}]);
%         disp(['Subject file:' FileList{curFileIx}]);
% 
%         datar = data(:,1:size(data,2)-2); % remove 2 trigger channel at the end
        
        %positions{iclass}(1):positions{iclass}(2)

        [epochs epochsIndex] = eeg2epochs_index(datar', window_movement ,overlap);

        %Nclass = 11; % skip rest

        NTesttrial = size(epochs,3);

        d = zeros(NTesttrial,Nclass);

        for i=1:NTesttrial

            for c=1:Nclass

                 d(i,c) = 0;
               
                 for j=1:cov_mat_per_class

                    switch j
                      case 1 
                           weight = 300;
                      case 2 
                           weight = 200;
                      case 3 
                           weight = 100; 
                    end;
                 
                    buffer = epochs(:, (j-1) * windows_sizes + 1 : j * windows_sizes ,i);
                    covv = covariances(buffer);
                    
                    d(i,c) = d(i,c) + distance(covv, CallClass{c,j}, method_dist);
                 end;

            end
        end

        [~,ix] = min(d,[],2);
        disp('Online completed');
        ix(ix == 12) = 0; %remove rest for visibility
        plot(ix);
        
        %% evaluate
         total=0;
         for c = 1:Nclass
             
             k= 0;
             %ii =0;
             for i = 1:length(ix)

                %ii = ii + 1;
                if (ix(i) == c && epochsIndex(i) >= start_of_class(c) && epochsIndex(i)<end_of_class(c))
                   k = k + 1;
                 end;
             end;
             
             total = total + k;
             %acc = k / ii;
             %disp(['class ' num2str(c) ' accuracy: ' int2str(acc*100) '%']);
             
         end;
         
         acc = total / length(ix);
         disp(['Total accuracy: ' int2str(acc*100) '%']);
         
         
        

% end;
%Ytest = labels(ix);

% 
% 
% Ytrain = Y;
% 
% 
% CallClass = cell(Nclass,1);
% 
% % estimation of center - actual classification
% for i=1:Nclass
%     CallClass{i} = mean_covariances(COVtest(:,:,Ytrain==labels(i)),method_mean);
% end